<?php

 function hypeLiveSearch_init() {
	
    register_page_handler('hypesearch', 'hypeLiveSearch_call');
    elgg_extend_view('css', 'hypeLiveSearch/css/css');
//    register_action("hypeLiveSearch/search", true, $CONFIG->pluginspath . "hypeLiveSearch/actions/search.php");
     
}

 function hypeLiveSearch_call($page) {
    global $CONFIG;

    if (!$q = get_input('q')) {
        exit;
    }

    $q = sanitise_string($q);
    
    $q = str_replace(array('_', '%'), array('\_', '\%'), $q);

    $limit = 50;
    
    $results = array();

    $query = "select valor.id, valor.string as address, geo.*, usr.username
              from
               {$CONFIG->dbprefix}users_entity usr
                join {$CONFIG->dbprefix}entities ent on ent.guid = usr.guid
                join {$CONFIG->dbprefix}metadata meta on ent.guid = meta.entity_guid
                join {$CONFIG->dbprefix}metastrings nome on meta.name_id = nome.id
                join {$CONFIG->dbprefix}metastrings valor on valor.id = meta.value_id
                join elgg_all_latlong geo on geo.entity_guid = meta.entity_guid
              where 
                nome.string = 'address_line_1' and 
                valor.string like '%$q%' ";

    if ($entities = get_data($query)) {
        foreach ($entities as $entity) {
        	
            $json = json_encode(array('desc' => $entity->address,
                                      'url' => $CONFIG->wwwroot . 'pg/locations/producer/' .$entity->username));
             $results[$entity->address . rand(1, 100)] = $json;
        }
    }

    ksort($results);
    echo implode($results, "\n");
    exit;
}

  register_elgg_event_handler('init', 'system', 'hypeLiveSearch_init');
  global $CONFIG;
  register_action("livesearch/search", true, $CONFIG->pluginspath . "hypeLiveSearch/actions/search.php");

?>